package com.msc.mc.spec;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.text.PDFTextStripper;

public class SpecHandler {

		public void readPdf() {
			
		}
		
		
		public static void main( String[] args ) throws IOException {
			//helloworld();
			extractTxt();
		}
		
		public static void extractTxt() throws IOException{
			String filePath = "/data/NIO-SM.51.009-2017.pdf";
			FileInputStream is  = new FileInputStream(filePath);
			PDDocument doc =  PDDocument.load( is );
			PDPage page = doc.getPage(0);
			PDFTextStripper stripper = new PDFTextStripper();
			stripper.setStartPage(2);
			stripper.setEndPage( 3 );
			String result = stripper.getText( doc );
		System.out.println( result );
			doc.close();
		}
		
		public static void helloworld() throws IOException {
			String filename = "/data/a.pdf";
	        String message =  "Hello world!!!";
	        
	        try (PDDocument doc = new PDDocument())
	        {
	            PDPage page = new PDPage();
	            doc.addPage(page);
	            
	            PDFont font = PDType1Font.HELVETICA_BOLD;

	            try (PDPageContentStream contents = new PDPageContentStream(doc, page))
	            {
	                contents.beginText();
	                contents.setFont(font, 12);
	                contents.newLineAtOffset(100, 700);
	                contents.showText(message);
	                contents.endText();
	            }
	            
	            doc.save(filename);
	        }
		}
		
		
		/**
		 * 
		 * @Title: getTextFromPdf
		 * @Description: 读取pdf文件内容
		 * @param filePath
		 * @return: 读出的pdf的内容
		 */
		public static String getTextFromPdf(String filePath) {
			String result = null;
			FileInputStream is = null;
			PDDocument document = new PDDocument();
			try {
				is = new FileInputStream(filePath);
				//PDFParser parser = new PDFParser(is);
				//parser.parse();
				//document = parser.getPDDocument();
				document = PDDocument.load( is );
				PDFTextStripper stripper = new PDFTextStripper();
				result = stripper.getText(document);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (document != null) {
					try {
						document.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

	
}
